# Title     : TODO
# Objective : TODO
# Created by: yz
# Created on: 2018/3/1

library(optparse)
library(magrittr)
library(viridis)
library(tidyverse)
library(extrafont)

option_list <- list(
  make_option("--base", default = "metabo_base.R", type = "character", help = "metabo base R file"),
  make_option("--pc", default = "", type = "character", help = "config file")

)
opt <- parse_args(OptionParser(option_list = option_list))
font_import(paths = c("/usr/share/fonts/myFonts"),recursive =F, prompt = F)

args <- commandArgs(trailingOnly = F)
scriptPath <- dirname(sub("--file=", "", args[grep("--file", args)]))
source(str_c(scriptPath, "/parse_config_json.R"))
baseFamily <- fontFamily
fileName <- "name_map.txt"

if (!file.exists(fileName)) {
  quit(status = 0)
}

nameMapDf <- read_tsv(fileName)

keggIds <- nameMapDf$KEGG
if (all(is.na(keggIds))) {
  quit(status = 0)
}

data <- read_csv("Pathway_Result.csv") %>%
  rename(Metabolite = X1)

if (nrow(data)==0) {
  quit(status = 0)
}

plotData <- data %>%
  rename(p = `Raw P`) %>%
  mutate(p = as.numeric(p), Impact = as.numeric(Impact)) %>%
  mutate(logP = -log(p)) %>%
  arrange(logP) %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite)))  %>%
  filter(Impact > 0)

parent <- "./"
p <- ggplot(plotData, mapping = aes(x = Metabolite, y = Impact)) +
  ylab("Impact") +
  xlab("") +
  theme_bw(base_size = 8.8, base_family = baseFamily) +
  theme(axis.text.x = element_text(size = 10, hjust = 1, vjust = 1), legend.position = 'right',
        legend.text = element_text(size = 9), legend.title = element_text(size = 11), axis.text.y = element_text(size = 10),
        axis.title.y = element_text(size = 11), axis.title.x = element_text(size = 12), panel.grid.major.x = element_blank(),
        panel.border = element_rect(size = 0.75), panel.grid.minor.x = element_blank(), panel.grid.major.y = element_blank(),
  ) +
  geom_col(aes(fill = logP)) +
  coord_flip()

p <- getBasicPlotArg(p)

if (!is.na(legendTitle)) {
  p <- p +
    scale_fill_gradientn(legendTitle, colors = finalColors)
}else {
  p <- p +
    scale_fill_gradientn("-ln(P)", colors = finalColors)
}


pdfFileName <- paste0(parent, "/Pathway_Barplot.pdf")
ggsave(limitsize = FALSE, pdfFileName, p, width = width, height = height)







